import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image_gallery_saver_plus/image_gallery_saver_plus.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:share_plus/share_plus.dart';
import '../../../utils/tips.dart';
import 'dart:ui' as ui;


String photoFolderName = 'photoTranslateDir';
String picUrl = 'https://xy-apis.newtranx.com/mt/v1/images';

class PhotoUtil {
  // 图片缩放显示到屏幕尺寸后，调整区域坐标
  static Map<String, dynamic> Function(dynamic res, dynamic scale) transPo = (
    res,
    scale,
  ) {
    var topLet = res['bounding'][0];
    var topRight = res['bounding'][1];
    var bottomRight = res['bounding'][2];
    var bottomLeft = res['bounding'][3];
    var nTopLeft = {'x': topLet['x'] * scale, 'y': topLet['y'] * scale};
    var nTopRight = {'x': topRight['x'] * scale, 'y': topRight['y'] * scale};
    var nBottomRight = {
      'x': bottomRight['x'] * scale,
      'y': bottomRight['y'] * scale,
    };
    var nBottomLeft = {
      'x': bottomLeft['x'] * scale,
      'y': bottomLeft['y'] * scale,
    };
    var nBounding = [nTopLeft, nTopRight, nBottomRight, nBottomLeft];
    return {
      'text': res['text'],
      'translation': res['translation'],
      'bounding': nBounding,
    };
  };

  // 根据屏幕尺寸调整坐标位置
  static adjustPosition(screenWidth, data) {
    var picWidth = data['content']['width'];
    var scale = screenWidth / picWidth;
    var calResult =
        data['content']['result'].map((item) => transPo(item, scale)).toList();
    return calResult;
  }

  //  文件操作相关方法
  //  创建文件夹
  static Future<Directory> createFolder() async {
    final path = await getTemporaryDirectory();
    final folderDirectory = Directory('${path.path}/${photoFolderName}');
    final newDirectory = await folderDirectory.create(recursive: true);
    return newDirectory;
  }

  //  删除文件夹
  static deleteDirectory() async {
    String path = '${(await getTemporaryDirectory()).path}/${photoFolderName}';
    final dir = Directory(path);
    if (dir.existsSync()) {
      dir.deleteSync(recursive: true);
      print('Directory deleted: $path');
    }
  }

  // 删除文件夹里的所有文件
  Future<void> deleteAllFilesInDirectoryAsync(String directoryPath) async {
    try {
      final dir = Directory(directoryPath);
      if (await dir.exists()) {
        await for (var entity in dir.list()) {
          if (entity is File) {
            await entity.delete();
          }
        }
      } else {
        print('Directory does not exist: $directoryPath');
      }
    } catch (e) {
      print('Error deleting files: $e');
    }
  }

  // 删除音频文件
  static Future<void> clearVoiceFile() async {
    // 查找是否有对应的文件存在
    final dir = await getTemporaryDirectory();
    final srcPath = '${dir.path}/audio_temp_src.mp3';
    File srcFile = File(srcPath);
    bool srcExists = await srcFile.exists();
    if (srcExists) {
      await File(srcPath).delete();
    }
    final tgtPath = '${dir.path}/audio_temp_tgt.mp3';
    File tgtFile = File(tgtPath);
    bool tgtExists = await tgtFile.exists();
    if (tgtExists) {
      await File(tgtPath).delete();
    }
    // audioPlayer.dispose(); // 释放资源
  }

  //  请求相关

  // 获取翻译结果
  static Future fetchTranslate(
    path,
    screenWidth,
    fromLanFlag,
    toLanFlag,
  ) async {
    Tips.showLoading();
    BaseOptions options = BaseOptions();
    options.headers["contentType"] = "multipart/form-data";
    options.headers["X-Api-Key"] = '264e03da4958e5ea405dd8f63b87da898757b821';
    try {
      Dio dio = new Dio(options);
      FormData formData = FormData.fromMap({
        'image': await MultipartFile.fromFile(path),
        'srcLang': fromLanFlag,
        'tgtLang': toLanFlag,
      });

      Response response = await dio.post(picUrl, data: formData);
      Tips.dismissLoading();
      // 处理服务器返回的响应数据
      if (response.statusCode == 200) {
        var resData = response.data["data"];
        // Map<String,dynamic>jsonMap = jsonDecode(response.data);
        print('resData ${resData}');
        if (resData['content']['result'].length == 0) {
          // Tips.showToast('未检测到文字');
          return null;
        }
        var transData = adjustPosition(screenWidth.toInt() - 0, resData);
        return transData;
      } else {
        Tips.dismissLoading();
        print('error1 $response.data');
        Tips.showToast('$response.data');
        return null;
      }
    } catch (error) {
      Tips.dismissLoading();
      print('error2 $error');
      // 异常处理
      Tips.showToast('$error');
      return null;
    }
  }

  // 分享文本
  static shareText(listArr) {
    var text = '';
    for (var i = 0; i < listArr.length; i++) {
      var textTitle = i == 0 ? 'Photo${i + 1}:\n' : '\n\nPhoto${i + 1}:\n';
      text = text + textTitle;
      var textItems =
          listArr[i]['resultText'].map((item) => '${item}\n').toList();
      for (var j = 0; j < textItems.length; j++) {
        text = text + textItems[j];
      }
    }
    SharePlus.instance.share(ShareParams(text: text, title: '分享文本'));
  }

  // 分享图片
  static sharePic(picArr) async {
    var files = [XFile("${picArr[0]['tgt']}")];
    for (var i = 0; i < picArr.length; i++) {
      if (i > 0) {
        final fileItem = XFile("${picArr[i]['tgt']}");
        files.add(fileItem);
      }
    }
    ;
    print('files${files}');
    final params = ShareParams(text: '分享图片', files: files);

    await SharePlus.instance.share(params);
  }

  // 授予权限返回true， 否则返回false
  static Future<bool> requestScopePermission() async {
    // 获取当前的权限
    PermissionStatus status = await Permission.storage.status;
    print('status${status}');
    if (status == PermissionStatus.granted) {
      // 已经授权
      return true;
    } else {
      // 未授权则发起一次申请
      status = await Permission.storage.request();
      if (status == PermissionStatus.granted) {
        return true;
      } else {
        return false;
      }
    }
  }

  static Future<dynamic> saveImage(String filePath) async {
    final file = File(filePath);
    final data = await file.readAsBytes(); //读取文件内容为Uinit8List;
    final byteData = ByteData.sublistView(data); //将Uint8List转换为ByteData
    Uint8List pngBytes = byteData.buffer.asUint8List();
    final result = await ImageGallerySaverPlus.saveImage(pngBytes);
    return result;
  }

  static Future<void> saveToAlbum(imageUrls) async {
    bool storageStatus = await requestScopePermission();
    if (storageStatus) {
      Map<String, dynamic> curRes = {'index': 0, 'isSuccess': true};
      for (int i = 0; i < imageUrls.length; i++) {
        var result = await saveImage(imageUrls[i]['tgt']);
        if (!result['isSuccess']) {
          Tips.showToast(result['errorMessage']);
          curRes['isSuccess'] = false;
        }
        curRes['index'] = i;
      }
      if (curRes['index'] == imageUrls.length - 1) {
        if (curRes['isSuccess']) {
          Tips.showToast('保存成功');
        }
      }
    } else {
      Tips.showToast('暂无相册授权');
    }
  }

//   获取图片高度
  static Future<double> getLocalImageHeight(String filePath,screenWidth) async {
    File file = File(filePath);
    Uint8List bytes = await file.readAsBytes();
    ui.Codec codec = await ui.instantiateImageCodec(bytes);
    ui.FrameInfo frameInfo = await codec.getNextFrame();
    ui.Image image = frameInfo.image;
    final picWidth = image.width;
    var scale = screenWidth / picWidth;
    return image.height.toDouble()*(scale.toDouble());
  }

  static showCheckDialog(BuildContext context, callback) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return Center(
          child:ConstrainedBox(
            constraints: BoxConstraints(maxWidth: 280),
              child:  CupertinoActionSheet(
                title: Text('错误',style:TextStyle(color:Color(0xFF333333),fontSize: 16),textAlign: TextAlign.center,),
                message: Container(
                    height: 96,
                    width: 280,
                    child:  Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text('未检测到文字',style:TextStyle(color:Color(0xFF333333),fontSize: 16)),
                      ],
                    )
                ),
                actions: <Widget>[
                  CupertinoActionSheetAction(
                      onPressed:(){
                        callback();
                        Navigator.pop(context, "确定");
                      } ,
                      child: Text('再试一次',style: TextStyle(color:Color(0xFF0D65E6),fontSize: 16),textAlign: TextAlign.center,))
                ],
              )
          ),

        );

      },
    );
  }


}
